package jalus.utils;

import jalus.model.File;
import jalus.model.Post;
import jalus.service.ConfigureService;
import jalus.service.FileService;
import jalus.service.PostService;
import jalus.service.TagService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;

public class MetaWeblogAPIHandler {

	@SuppressWarnings("unchecked")
	public String newPost(String blogid, String userName, String password,	Map struct, Boolean publish)
			throws Exception {
		User user = checkUser(userName, password);
		if(user == null){
			throw new Exception("access denied");
		}
		// Parse values from struct corresponding to RSS specification.
		String title = (String) struct.get("title");
		String description = (String) struct.get("description");
		description = HttpUtils.tranlateSourceCode(description);
		List<String> tagList = new ArrayList<String>();
		if(struct.containsKey("categories")){
			List<Object> l = Arrays.asList((Object[])struct.get("categories"));
			for(Object o : l){
				tagList.add((String)o);
			}
		}
		Date date;
		/* wlm提交的日期有：
		 * dateCreated
		 * date_created_gmt*/
		if(struct.containsKey("date_created_gmt")){
			date = (Date)struct.get("date_created_gmt");
		}else{
			date = new Date();
		}
		Post post = new Post(user,title, 1, new Text(description),date, tagList);
		Long id = PostService.getInstance().addPost(post);
		return (id.toString());
	}

	@SuppressWarnings("unchecked")
	public Boolean editPost(String blogId, String userName, String password,Map struct, Boolean publish)
			throws Exception {
		User user = checkUser(userName, password);
		if(user == null){
			throw new Exception("access denied");
		}
		
		Long id = new Long(blogId);
		String title = (String) struct.get("title");
		String description = (String) struct.get("description");
		description = HttpUtils.tranlateSourceCode(description);
		List<String> tagList = new ArrayList<String>();
		if(struct.containsKey("categories")){
			List<Object> l = Arrays.asList((Object[])struct.get("categories"));
			for(Object o : l){
				tagList.add((String)o);
			}
		}
		Post post = new Post(user,title, 1, new Text(description),new Date(), tagList);
		post.setId(id);
		post.setLast_modify_by(user);
		Date date;
		if(struct.containsKey("date_created_gmt")){
			date = (Date)struct.get("date_created_gmt");
		}else{
			date = new Date();
		}
		post.setLast_modify_date(date);
		PostService.getInstance().updatePost(post);
		
		return (new Boolean(true));

	}

	@SuppressWarnings("unchecked")
	public Map getPost(String postId, String userName, String password) throws Exception {
		User user = checkUser(userName, password);
		if(user == null){
			throw new Exception("access denied");
		}
		Long id = new Long(postId);
		jalus.pojo.Post post = PostService.getInstance().getPostById(id);
		HashMap result = new HashMap();
		result.put("postid", postId);
		result.put("dateCreated", post.getDate());
		result.put("title", post.getTitle());
		result.put("description", post.getContent());
		result.put("categories", post.getTags());
		result.put("publish", true);
		return (result);

	}
	
	@SuppressWarnings("unchecked")
	public Object[] getCategories(String blogid, String userName, String password) throws Exception{
		User user = checkUser(userName, password);
		if(user == null){
			throw new Exception("access denied");
		}
		List<jalus.pojo.Tag> tagList = TagService.getInstance().getAllTag();
		List<Map> tagNameList = new ArrayList<Map>(tagList.size());
		for(jalus.pojo.Tag tag : tagList){
			HashMap map = new HashMap();
			map.put("title", tag.getName());
			map.put("description", tag.getName());
			tagNameList.add(map);
		}
		return tagNameList.toArray();
	}
	
	public Boolean deletePost(String appkey, String postId, String userName, String password, Boolean publish)
			throws Exception{
		User user = checkUser(userName, password);
		if(user == null){
			throw new Exception("access denied");
		}
		Long id = new Long(postId);
		PostService.getInstance().deletePostById(id);
		return new Boolean(true);
	}

	@SuppressWarnings("unchecked")
	public Object[] getRecentPosts(String blogId, String userName, String password, Integer numberOfPosts) 
			throws Exception{
		User user = checkUser(userName, password);
		if(user == null){
			throw new Exception("access denied");
		}
		List<jalus.pojo.Post> postList = PostService.getInstance().getRecentPost(numberOfPosts);
		List result = new ArrayList(postList.size());
		for(jalus.pojo.Post post : postList){
			HashMap map = new HashMap();
			map.put("postid", post.getId().toString());
			map.put("dateCreated", post.getDate());
			map.put("title", post.getTitle());
			map.put("description", post.getContent());
			map.put("categories", post.getTags());
			map.put("publish", true);
			result.add(map);
		}
		return result.toArray();
	}
	
	@SuppressWarnings("unchecked")
	public Object[] getUsersBlogs(String appkey, String userName, String password)
			throws Exception {
		User user = checkUser(userName, password);
		if(user == null){
			throw new Exception("access denied");
		}
		String url = ConfigureService.getInstance().getHost();
		String blogName =  ConfigureService.getInstance().getBlogTitle();

		Map returnMe[] = new Map[1];
		returnMe[0] = new HashMap();
		returnMe[0].put("userID", user.getNickname());
		returnMe[0].put("url", url);
		returnMe[0].put("blogid", "jalus");
		returnMe[0].put("blogName", blogName);

		return (returnMe);
	}
	
	@SuppressWarnings("unchecked")
	public Map newMediaObject(String blogId, String userName, String password, Map struct) throws Exception{
		User user = checkUser(userName, password);
		if(user == null){
			throw new Exception("access denied");
		}
		//TODO: struct.name filename;相同的文件名应是覆盖关系
		String fileName = (String)struct.get("name");
		String mimeType = (String)struct.get("type");
		byte[] data = (byte[])struct.get("bits");
		
		Blob blob = new Blob(data);
		File file = new File(fileName, mimeType, blob, new Date());
		Long id = FileService.getInstance().add(file);
		
		String url = HttpUtils.connectUrl(ConfigureService.getInstance().getHost(), "showimage", id.toString());
		HashMap map = new HashMap();
		map.put("url", url);
		return map;
	}
	
	@SuppressWarnings("unchecked")
	public Map getUserInfo(String key, String userName, String password){
		HashMap map = new HashMap();
		map.put("nickname", "dongliu");
		map.put("userid", "dongliu");
		map.put("url", ConfigureService.getInstance().getHost());
		map.put("email", "");
		map.put("lastname", "");
		map.put("firstname", "");
		return map;
	}
	
	private User checkUser(String userName, String password){
		if(!(userName.equals(ConfigureService.getInstance().getMetaWeblogUserName()) && 
				password.equals(ConfigureService.getInstance().getMetaWeblogPassword()))){
			return null;
		}
		
		String[] userinfo = ConfigureService.getInstance().getPicasaUserName().split("@");
		User user = new User(ConfigureService.getInstance().getPicasaUserName(), userinfo[1]);
		return user;
		
	}
}
